import { clone, isUndefined } from "xe-utils";

export default {
  data() {
    return {
      loading: false,
      sort: null,
      order: null,
      pagination: {
        page: 1,
        size: 10,
        total: 0,
        sizes: [10, 20, 50, 100],
        layout: "->, total, sizes, prev, pager, next, jumper",
      },
    };
  },
  methods: {
    getParams(params) {
      if (!isUndefined(params)) {
        this.resetPaginationParams();
      }
      let queryParams = [];
      // INCOMPATIBLE_FIELD 位于页面同级目录下 config.js , 用于字典类型和接口类型不匹配时自动转换
      if (this.$refs.refQueryForm?.queryForm) {
        queryParams = clone(this.$refs.refQueryForm.queryForm);
        const queryParamsKeys = Object.keys(queryParams);
        queryParamsKeys.forEach((key) => {
          const handler = this.INCOMPATIBLE_FIELD?.[key];
          const paramValue = queryParams[key];
          if (handler) {
            queryParams[key] = handler[1](paramValue);
          }
          // 适应后端接口查询参数要传递字典 value 的情况, 正常使用的是 key
          // key:"0"
          // value:"否"
          if (paramValue === "全部") {
            delete queryParams[key];
          }
        });
      }
      const { page, size } = this.pagination;

      const baseParams = {};
      if (this.sort && this.order) {
        baseParams.sort = this.sort;
        baseParams.order = this.order;
      }
      Object.assign(baseParams, { pageIndex: page, length: size }, queryParams);
      return baseParams;
    },
    onSizeChange(size) {
      this.pagination.size = size;
      this.getDataList();
    },
    onCurrentChange(page) {
      this.pagination.page = page;
      this.getDataList();
    },
    onSortChange(params) {
      if (params.order) {
        this.sort = params.prop;
        this.order = params.order === "ascending" ? "asc" : "desc";
      } else {
        this.sort = null;
        this.order = null;
      }
      this.getDataList();
    },
    resetPaginationParams() {
      this.pagination.page = 1;
      this.pagination.size = 10;
    },
    columnIndex(index) {
      return index + 1 + (this.pagination.page - 1) * this.pagination.size;
    },
  },
};
